package handler

import (
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"log"
	"tong/global"
	"tong/request"
	"tong/response"
)

/**
{
    "cmd":"send",
    "data":{
        "to_user_id": 2,
        "message":"hello 2"
    }
}
*/

func Chat(c *gin.Context) {

	//get middle userId
	userId := c.GetUint("userId")

	// update websocket
	var upgrader = websocket.Upgrader{} // use default options

	conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		log.Print("upgrade:", err)
		response.WsResponseError(c, -1, "失败", err)
		return
	}

	defer conn.Close()

	//online user data
	global.OnlineUser[userId] = conn
	fmt.Println("yh", global.OnlineUser, userId)
	for {
		_, message, err := conn.ReadMessage()
		if err != nil {
			log.Println("read:", err)
			break
		}

		var req request.WSReq

		err = json.Unmarshal(message, &req)
		if err != nil {

			response.WSRespErr(conn, 1000, "非法入参illegal json")
			continue
		}

		switch req.Cmd {
		case "send":
			go Send(conn, message)
		default:
			response.WSRespErr(conn, 10001, "no function")
		}

	}

}

func Send(conn *websocket.Conn, message []byte) {

	var req request.WSSendReq
	err := json.Unmarshal(message, &req)
	if err != nil {
		response.WSRespErr(conn, 20001, "入参错误Parsing json failed ")
		return
	}

	if req.Data.ToUserId < 1 {
		response.WSRespErr(conn, 20002, " 用户未上线 not ToUserId params")
		return
	}

	if req.Data.Message == "" {
		response.WSRespErr(conn, 20004, "没有信息not Message params")
		return
	}

	if global.OnlineUser[req.Data.ToUserId] == nil {
		response.WSRespErr(conn, 20003, "没有登录not online")
		return
	}

	response.WSRespSuccess(global.OnlineUser[req.Data.ToUserId], req.Data.Message)

	response.WSRespSuccess(conn, "发送成功send ok")

}
